﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using jSLApp.Client.Controls;
using jSLApp.Client.Forms;
using jSLApp.Client.Workflow;
using jSLCore.Client.Presentation;
using jSLCore.Client.Presentation.ApplicationContainer;
using jSLCore.Client.Presentation.Authorization;
using jSLCore.Client.Presentation.Authorization.Managment;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Presentation.Common;

namespace jSLApp.Client.ApplicationBase
{
    public partial class MainContentContainer : ContentContainerBase
    {
        public MainContentContainer()
        {
            InitializeComponent();
        }

        public override void GotoIndexedPage(string key, string value)
        {
            switch (key)
            {
                case PageNames.FilmDetail:
                    try
                    {
                        ShowFilm(int.Parse(value));
                    }

                    catch (FormatException)
                    {
                    }
                    catch (OverflowException)
                    {
                    }
                    catch (ArgumentNullException)
                    {
                    }
                    break;

                case PageNames.EmailVerificationCode:
                    var verCode = value;
                    Guid rescode;
                    if (Guid.TryParse(verCode, out rescode))
                    {
                        DoWork("Подтверждение регистрации", (sender, args) => Communication.Proxy.SubmitEMail(args.Guid), (o, eventArgs) =>
                        {
                            if (eventArgs.Error == null)
                            {
                                InfoBox.ShowDialog("Ваш адрес электронной почты подтвержден. Ваш аккаунт разблокирован.Окно будет закрыто автоматически.");
                                ReloadWithOutParameters();
                            }
                        }, rescode);
                    }
                    else
                    {
                        ErrorBox.ShowDialog("Неверный код подтверждения");
                    }
                    break;

                case PageNames.PwdChangeVerificationCode:
                    var chCode = value;
                    var reschcode = new Guid();
                    if (Guid.TryParse(chCode, out rescode))
                    {
                        var dlg = new jAskForStringBox("Укажите новый пароль:", "", false);
                        dlg.ShowDialog(delegate(object sender, object data)
                        {
                            var str = data as string;
                            if (!string.IsNullOrEmpty(str))
                            {
                                DoWork("Смена пароля", (o, args) => Communication.Proxy.SubmitPasswordChange(
                                    args.Guid, (string)args.Params[1]), (sender1, eventArgs) =>
                                    {
                                        if (eventArgs.Error == null)
                                        {
                                            InfoBox.ShowDialog("Пароль изменен. Окно будет закрыто автоматически");
                                            ReloadWithOutParameters();
                                        }
                                    }, reschcode, str);
                            }
                            else
                            {
                                ErrorBox.ShowDialog("Необходимо указать пароль. Попробуйте еще раз.");
                            }
                        }, this);
                    }
                    else
                    {
                        ErrorBox.ShowDialog("Неверный код подтверждения");
                    }
                    break;
             
            }
        }

        private void ReloadWithOutParameters()
        {
            SLWPFSelector.ReloadHtmlPage(this);
        }

        public override void ShowPage(BaseControl control, bool asDialog)
        {
            base.ShowPage(control, asDialog);
            BindPage(control);
        }

        private void BindPage(BaseControl control)
        {
            //Подсвечиваем нужный линк
            if(control is StartPage)
            {
                searchLink.Background = mainLink.Background;
                mainLink.Background = (Brush) Application.Current.Resources["orangeBorder"];
            }

            if (control is FilmList)
            {
                mainLink.Background = searchLink.Background;
                searchLink.Background = (Brush)Application.Current.Resources["orangeBorder"];
            }
        }

        protected override BaseControl GetDefaultPage()
        {
            return new StartPage();// new FilmList(); //new FilmDetail(171);
        }

        protected override ContentPresenter GetMainContentPresenter()
        {
            return mainContent;
        }

        protected override ContentPresenter GetOkCancelControlContentPresenter()
        {
            return okCancelPresenter;
        }

        public static MainContentContainer Current
        {
            get { return (MainContentContainer) ApplicationContainer.CurrentContentContainer; }
        }

        private void addFilm_Clicked(object sender, RoutedEventArgs e)
        {
            var newFilm = new NewFilm();
            newFilm.ShowDialog(delegate(object o, object data)
                                   {
                                       ShowFilm((int) data);
                                   }, this);
        }

        internal void ShowFilm(int id)
        {
            try
            {//todo: тут падало, надо разобраться
                ParentApplicationContainer.CloseAllDialogs();
            }
            catch (NullReferenceException)
            {
                
            }

            var dlg = new FilmDetail(id);
            dlg.ShowDialog();
            //NavigateTo(dlg,false);
            //throw new NotImplementedException();
        }

        private void goDefault_Clicked(object sender, RoutedEventArgs e)
        {
            NavigateTo(GetDefaultPage(),false);
        }

        private void search_Clicked(object sender, RoutedEventArgs e)
        {
            Search();
        }

        private void Search(string keyWord=null)
        {
            NavigateTo(new FilmList(keyWord),false);
        }

        public override void LoadInitialData()
        {
            base.LoadInitialData();
            jSecurity.SecurityChanged += (sender, args) => CheckConstants();
            
            CheckConstants();
            
            

            Bind("security");

            ParentApplicationContainer.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"/jSLApp.Client;component/Resources/Common.xaml", UriKind.RelativeOrAbsolute) });
            ParentApplicationContainer.Foreground = new SolidColorBrush(Colors.White);
#if !DEBUG
            ShowAbout();
#endif
        }

        private void ShowAbout()
        {
            new About().ShowDialog(this);
        }

        public void CheckConstants()
        {
            DoWork(true, (o, eventArgs) => Communication.Proxy.SiteVisit(), (sender1, completedEventArgs) => { });
            CheckBalance();
            CheckAge();
            CheckUserName();
        }

        private void CheckUserName()
        {
            if(jSecurity.IsAuthorized)
            {
                userName.Content = jSecurity.Login.Trim();
            }
            else
            {
                userName.Content = null;
            }
        }

        private void CheckAge()
        {
            if(jSecurity.IsAuthorized)
            {
                DoWork(true,(sender, args) =>
                                {
                                    args.Result = Communication.Proxy.GetAgeOfCurrentUser();
                                },(o, eventArgs) =>
                                                      {
                                                          if(eventArgs.Error==null)
                                                          {
                                                              DataHelper.AgeDone = (bool) eventArgs.Result;
                                                          }
                                                      });
            }
        }

        private void CheckBalance()
        {
            if(jSecurity.IsAuthorized)
            {
                DoWork("Обновление баланса",(sender, args) =>
                                                {
                                                    args.Result = Communication.Proxy.GetCurrentBalance();
                                                },(o, eventArgs) =>
                                                      {
                                                          if(eventArgs.Error==null)
                                                          {
                                                              var balance = (decimal)eventArgs.Result;
                                                              balanceTxt.Content = string.Format("{0} р.", balance);
                                                          }
                                                      });
            }
        }

        private void UpdateBalance_Clicked(object sender, RoutedEventArgs e)
        {
            CheckConstants();
        }

        private void goPersonal_Clicked(object sender, RoutedEventArgs e)
        {
            if (jSecurity.Login != null)
            {
                var dlg = new PersonalPage(jSecurity.Login.Trim());
                dlg.ShowDialog(null,null,(o, args) => CheckConstants(),true,this);
            }
        }

        private void gotoUsers_Clicked(object sender, RoutedEventArgs e)
        {
            ShowPage(new UserList(), false);
        }

        private void gotoManagment_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new ManagmentPanel();
            NavigateTo(dlg);
        }

        public void SendEMail(string toLogin)
        {
            var dlg = new jAskForStringBox("Текст письма:", string.Empty, true);
            dlg.ShowDialog(delegate(object sender, object data)
            {
                var message = data as string;

                if (!string.IsNullOrEmpty(message))
                {
                    DoWork("Отправка письма", (o, args) =>
                    {
                        Communication.Proxy.SendMailToUser(args.String, (string)args.Params[1]);
                    }, (sender1, eventArgs) =>
                    {
                        if (eventArgs.Error == null)
                        {
                            InfoBox.ShowDialog("Письмо отправлено. Пользователь сможет ответить непосредственно на ваш e-mail.");
                        }
                    }, toLogin, message);
                }
            }, this);
        }

        private void gotoLogs_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new LogList();
            ShowPage(dlg, false);
        }

        private void goUserPwd_Clicked(object sender, RoutedEventArgs e)
        {
            var dlg = new AccountDetail();
            dlg.ShowDialog(this);
        }

        private void Logout_Clicked(object sender, RoutedEventArgs e)
        {
            ParentApplicationContainer.Logout(null);
        }

        private void enter_Clicked(object sender, RoutedEventArgs e)
        {
            ParentApplicationContainer.ShowAuthorizationDialog(true,null);
        }
      

        private void getHelp_Clicked(object sender, RoutedEventArgs e)
        {
            ShowAbout();
        }

        private void sendFeedback_Clicked(object sender, RoutedEventArgs e)
        {
            SendFeedback();
        }

        private void SendFeedback()
        {
            new SendMail().ShowDialog();
        }

        private void search_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key==Key.Enter)
            {
                Search(searchTxt.Value.ToString());
            }
        }
    }
}
